package com.kamistoat.meimeimall.meimeimallmember.service.impl;

import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.kamistoat.meimeimall.common.To.memberTo.MemberReceiveAddressTo;
import com.kamistoat.meimeimall.common.annotation.ClearCache;
import com.kamistoat.meimeimall.common.annotation.WithCache;
import com.kamistoat.meimeimall.common.constant.DatabaseConstant;
import com.kamistoat.meimeimall.common.exception.BizCodeEnum;
import com.kamistoat.meimeimall.common.exception.RRException;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.kamistoat.meimeimall.meimeimallmember.dao.MemberReceiveAddressDao;
import com.kamistoat.meimeimall.meimeimallmember.entity.MemberReceiveAddressEntity;
import com.kamistoat.meimeimall.meimeimallmember.service.MemberReceiveAddressService;
import org.springframework.transaction.annotation.Transactional;


@Service("memberReceiveAddressService")
public class MemberReceiveAddressServiceImpl extends ServiceImpl<MemberReceiveAddressDao, MemberReceiveAddressEntity> implements MemberReceiveAddressService {



    /**
     * 计算运费
     *
     * @param attrId
     * @return
     */
    @Override
    public BigDecimal getFare(Long attrId) {
        MemberReceiveAddressEntity addressEntity = this.getById(attrId);
        // TODO 直接使用物流公司的第三方接口即可。这里用手机号后一位做运费
        String fare = addressEntity.getPhone().substring(addressEntity.getPhone().length() - 1);
        return new BigDecimal(fare);
    }

    /**
     * 带缓查询用户收货地址列表。构造成To类返回.
     * 默认收获地址排在最前面
     *
     * @param memberId 用户Id
     */
    @Override
    @WithCache(prefix = "member:receiveAddressToList:#memberId", isList = true, returnType = MemberReceiveAddressTo.class)
    public List<MemberReceiveAddressTo> getMemberReceiveAddressToList(Long memberId) {
        List<MemberReceiveAddressEntity> memberReceiveAddressEntityList = this.list(
                new QueryWrapper<MemberReceiveAddressEntity>()
                        .eq("member_id", memberId)
                        .eq("logistic_deleted", DatabaseConstant.UN_LOGISTIC_DELETED)
                        .orderByDesc("default_status"));
        return memberReceiveAddressEntityList.stream().map(memberReceiveAddressEntity -> {
            MemberReceiveAddressTo memberReceiveAddressTo = new MemberReceiveAddressTo();
            BeanUtils.copyProperties(memberReceiveAddressEntity, memberReceiveAddressTo);
            return memberReceiveAddressTo;
        }).collect(Collectors.toList());
    }

    /**
     * 带缓查询指定Id的收货地址To类. 优先从缓存中用户地址列表中查询
     *
     * @param addrId
     */
    @Override
    public MemberReceiveAddressTo getReceiveAddressById(Long memberId, Long addrId) {
        List<MemberReceiveAddressTo> memberReceiveAddressToList = getMemberReceiveAddressToList(memberId);
        List<MemberReceiveAddressTo> selected = memberReceiveAddressToList.stream().filter((to) -> {
            return to.getId().equals(addrId);
        }).collect(Collectors.toList());
        if (selected.size() > 0) {
            return selected.get(0);
        } else {
            return null;
        }
    }

    /**
     * 带缓删除一个指定的收获地址
     *
     * @param memberId  用户Id
     * @param addressId 地址Id
     */
    @Override
    @ClearCache(prefix = "member:receiveAddressToList:#memberId")
    @Transactional
    public void deleteOneAddress(Long memberId, Long addressId) {
        // 带缓删除
        MemberReceiveAddressEntity deleteOne = this.getOne(new QueryWrapper<MemberReceiveAddressEntity>()
                .select("id", "member_id", "default_status")
                .eq("id", addressId)
                .eq("member_id", memberId)
                .eq("logistic_deleted", DatabaseConstant.UN_LOGISTIC_DELETED));
        if (deleteOne == null) {
            throw new RRException(BizCodeEnum.RECEIVE_ADDRESS_NOT_EXIST.getMessage(), BizCodeEnum.RECEIVE_ADDRESS_NOT_EXIST.getCode());
        }
        // 非默认地址
        if (deleteOne.getDefaultStatus() == 0) {
            this.update(new UpdateWrapper<MemberReceiveAddressEntity>()
                    .set("logistic_deleted", DatabaseConstant.LOGISTIC_DELETED)
                    .eq("id", deleteOne.getId()));
        }
        // 是默认地址
        else {
            this.update(new UpdateWrapper<MemberReceiveAddressEntity>()
                    .set("logistic_deleted", DatabaseConstant.LOGISTIC_DELETED)
                    .eq("id", deleteOne.getId()));
            List<MemberReceiveAddressEntity> addressLimit = this.getBaseMapper().getRandomLimit(memberId, 1);
            if (addressLimit != null && addressLimit.size() > 0) {
                this.update(new UpdateWrapper<MemberReceiveAddressEntity>()
                        .set("default_status", 1)
                        .eq("id", addressLimit.get(0).getId()));
            }
        }
    }

    /**
     * 带缓修改一个指定收获地址为默认地址
     *
     * @param memberId  用户Id
     * @param addressId 地址Id
     */
    @Override
    @ClearCache(prefix = "member:receiveAddressToList:#memberId")
    @Transactional
    public void setToDefault(Long memberId, Long addressId) {
        MemberReceiveAddressEntity targetOne = this.getOne(new QueryWrapper<MemberReceiveAddressEntity>()
                .select("id", "member_id", "default_status")
                .eq("id", addressId)
                .eq("member_id", memberId)
                .eq("logistic_deleted", DatabaseConstant.UN_LOGISTIC_DELETED));
        if (targetOne == null) {
            throw new RRException(BizCodeEnum.RECEIVE_ADDRESS_NOT_EXIST.getMessage(), BizCodeEnum.RECEIVE_ADDRESS_NOT_EXIST.getCode());
        }

        // 原先的默认地址
        MemberReceiveAddressEntity existedOne = this.getOne(new QueryWrapper<MemberReceiveAddressEntity>()
                .select("id", "member_id", "default_status")
                .eq("id", addressId)
                .eq("member_id", memberId)
                .eq("default_status", 1)
                .eq("logistic_deleted", DatabaseConstant.UN_LOGISTIC_DELETED));

        this.update(new UpdateWrapper<MemberReceiveAddressEntity>()
                .set("default_status", 1)
                .eq("id", targetOne.getId()));

        this.update(new UpdateWrapper<MemberReceiveAddressEntity>()
                .set("default_status", 0)
                .eq("id", existedOne.getId()));
    }

    /**
     * 带缓修改/新增一个收获地址
     *
     * @param memberReceiveAddressTo
     */
    @Override
    @ClearCache(prefix = "member:receiveAddressToList:#memberId")
    @Transactional
    public void addOrUpdateAddress(MemberReceiveAddressTo memberReceiveAddressTo) {
        MemberReceiveAddressEntity entity = new MemberReceiveAddressEntity();
        BeanUtils.copyProperties(memberReceiveAddressTo, entity);
        // 添加，必然成为默认地址
        if (entity.getId() == null) {
            this.save(entity);
            setToDefault(entity.getMemberId(), entity.getId());
        } else {
            this.updateById(entity);
        }
    }
}